<?php

namespace App\Http\Controllers\Api\Login;

use App\Enum\enum_wechat;
use App\Http\Controllers\Api\ApiBaseController;
use App\Http\Format\FormatBase;
use App\Models\CityChinaModel;
use App\Models\ConfigModel;
use App\Models\GoodsModel;
use App\Models\OpLogsModel;
use App\Models\OrderModel;
use App\Models\PayConfigModel;
use App\Models\PetsModel;
use App\Models\SysUserModel;
use App\Models\TableItemModel;
use App\Models\TableModel;
use App\Models\TagsModel;
use App\Models\TaskTagModel;
use App\Models\TokenModel;
use App\Models\UserAreaLogsModel;
use App\Models\UserMessageModel;
use App\Models\UserModel;
use App\Models\UserMsmLogsModel;
use App\Models\UserPublicModel;
use App\Models\UserPublicSearchModel;
use App\Models\UserSignModel;
use App\Models\UserTokenModel;
use App\Services\Api\UserService;
use App\Services\CurlBasiceService;
use App\Services\Web\TaskService;
use App\Tools\AliyunSmsTool;
use App\Tools\AliyunUploadTool;
use App\Tools\WechatPayV2;
use App\Tools\WechatPhone;
use Illuminate\Http\Request;
use Exception;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class UserController extends ApiBaseController
{

    /**
     * 使用code，获取openid，返回token
     * @param Request $request
     * @return object|null
     * @throws Exception
     */
    public function auth_code(Request $request):?object
    {
        $params = $request->only(['code', 'share_token']);

        $wxxcx_config = config('wechat.wxxcx');
        //拼接参数
        $realUrl = enum_wechat::USER_AUTHOR;
        $realUrl = str_replace("JS_CODE", $params['code'] ?? '', $realUrl);
        $realUrl = str_replace("APPID", $wxxcx_config['app_id'] ?? '', $realUrl);
        $realUrl = str_replace("SECRET", $wxxcx_config['app_secret'] ?? '', $realUrl);
        //curl请求
        $result = CurlBasiceService::getInstance()->httpGet($realUrl);

        //数据库操作，返回token
        $token = UserService::getInstance()->getUserCode(json_decode($result, true), $params['share_token'] ?? '');

        if (empty($token[0])){
            return $this->codeError([], 1011, '参数错误');

        }

        //获取access_token
        $accessToken = TokenModel::getSingle();

        return $this->codeSuccess([
            'token'=>$token[0],
            'access_token'=>$accessToken['token'] ?? ''
        ]);

    }

    public function upload(Request $request):?object
    {
        //获取图片的扩展名
        $file = $request->file('file');
        $extension = $file->getClientOriginalExtension();

        $name = $extension;

        //定义新的文件名
        $name_pix = time() . rand(1000,9999);
        $filename= 'oss_img/' . date('Y-m-d').'/' . $name_pix;

        // public_path 是以 public 文件夹为根目录
        $isPath = public_path('oss_img/');
        // 1、先检查文件夹是否存在；2、不存在则新建文件夹
        File::isDirectory($isPath) or File::makeDirectory($isPath, 0777, true, true);

        $r = Storage::disk()->put($filename,$file);

        return $this->codeSuccess([
            'file'=> 'storage/' . $r
        ]);

    }

    /**
     * 填充用户信息
     * @param Request $request
     * @return object|null
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function fill_user_data(Request $request):?object
    {
        $params = $request->only(['mobile', 'area_province_id', 'area_city_id', 'area_district_id', 'head_img_url', 'nickname', 'is_admin']);

        if (empty($params['is_admin'])){
            //判断修改时间
            $res = UserAreaLogsModel::getUserAll(['user_id'=>  adminUserInfo('id'), ['created_at', '>', time()-(86400*365)]]);

            if (count($res) >= 2){
                return $this->codeError([], 1011, '每年只能修改2次');
            }

            $res1 = UserAreaLogsModel::getUserAll(['user_id'=>  adminUserInfo('id'), ['created_at', '>', time()-(86400*90)]]);
            if (count($res) >= 1){
                return $this->codeError([], 1011, '每季度只能修改1次');
            }

            //记录日志
            UserAreaLogsModel::insertSingle([
                'created_at'=> time(),
                'user_id'=> adminUserInfo('id')
            ]);
        }
        unset($params['is_admin']);

        //数据库操作
        UserService::getInstance()->dealtUserData($params);

        return $this->codeSuccess();
    }

    /**
     * 根据code获取手机号
     * @param Request $request
     * @return object|null
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function get_wx_phone(Request $request):?object
    {
        $params = $request->only(['code']);

        if (empty($params['code'])){
            return $this->codeError([], 1011, 'code不能为空');
        }

        $accessToken = TokenModel::getSingle();
        $wxxcx_config = config('wechat.wxxcx');

        $reslut = $this->getWxPhoneNumber($params['code'], $wxxcx_config['app_id'], $wxxcx_config['app_secret'], $accessToken['token']);
        $reslut = json_decode($reslut,true);
        if (empty($reslut['phone_info'])){
            return $this->codeError([], 1011, 'code与token不一致');
        }

        return $this->codeSuccess([
            'phone'=> $reslut['phone_info'],
        ]);
    }

    public function getWxPhoneNumber($code, $appid, $secret, $token)
    {
        $url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=' . $token;

        $data = json_encode(["code" => $code]);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POST, true);        // 发送post请求
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // 传入post参数

        $res = curl_exec($ch);
        curl_close($ch);

        return $res;
    }


    /**
     * 用户详情
     * @param Request $request
     * @return object|null
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function init(Request $request):?object
    {
        $userOne = adminUserInfo();

        //获取access_token
        $accessToken = TokenModel::getSingle();

        $userOne['area_province_msg'] = $this->handleCity($userOne['area_province_id']);
        $userOne['area_city_msg'] = $this->handleCity($userOne['area_city_id']);
        $userOne['area_district_msg'] = $this->handleCity($userOne['area_district_id']);

        return $this->codeSuccess([
            'token'=> $request->header('token'),
            'access_token'=>$accessToken['token'] ?? '',
            'data'=> $userOne
        ]);
    }

    public function handleCity($params_city){
        $temp_name = '';
        if (!empty($params_city)){
            $area_province_id = CityChinaModel::getSingle(['code'=>$params_city]);
            if ($area_province_id['name']){
                $temp_name = $area_province_id['name'];
            }
        }

        return $temp_name;
    }

    /**
     * 手机发送短信
     * @param Request $request
     * @return object|null
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function send_tel_code(Request $request):?object
    {
//        //生成二维码，上传阿里云oss
//        $qrUrl = 'https://farm-api.yydnc.cn/user/pets_detail?id=' . 1;
//        $qrName = time() . rand(1000, 9999) .'qrcode.png';
//        $qrPath = public_path('image/'. $qrName);
//        QrCode::format('png')->generate($qrUrl, $qrPath);
//
//        //上传阿里云
//        $object = 'api/' . date('Ymd', time()) . '/' . $qrName;
//        (new AliyunUploadTool())->uploadFile('farm-sheep', $object, $qrPath);
//
//        //拼接oss地址
//        $pix = config('wechat.oss.url');
//        $petsQrcode = $pix . $object;
//        D($petsQrcode);

        $params = $request->only(['mobile']);

        $rand = rand(10000, 99999);
        //发送短信
        $result = AliyunSmsTool::main($params['mobile'], $rand);

        if (!$result){
            return $this->codeError([], 1011, '短信发送失败');

        }

        //发送成功入库
        UserMsmLogsModel::insertSingle([
            'code'=> $rand,
            'phone'=> $params['mobile'],
            'user_id'=> adminUserInfo('id'),
            'created_at'=> time(),
        ]);

        return $this->codeSuccess();
    }

    /**
     * 手机发送短信
     * @param Request $request
     * @return object|null
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function login_tel_code(Request $request):?object
    {
        $params = $request->only(['mobile', 'sms_code']);

        //发送成功入库
        $userSms = UserMsmLogsModel::getSingle([
                ['phone', '=', $params['mobile']],
                [ 'created_at', '>', time() - 300]
            ]
        );

        if ($userSms['code'] <> $params['sms_code']){
            //验证不通过
            return $this->codeError([], 1019, '验证码校验失败');

        }

        //成功，写入用户表
        UserModel::updateSingle(['id'=> adminUserInfo('id')], ['mobile'=> $params['mobile']]);

        return $this->codeSuccess();
    }



    public function handle_phone(Request $request): ?Object
    {
        $param = $request->only(['code', 'encryptedData', 'iv']);

        //获取sessionKey
        $wxxcx_config = config('wechat.wxxcx');
        //拼接参数
        $realUrl = enum_wechat::USER_AUTHOR;
        $realUrl = str_replace("JS_CODE", $param['code'] ?? '', $realUrl);
        $realUrl = str_replace("APPID", $wxxcx_config['app_id'] ?? '', $realUrl);
        $realUrl = str_replace("SECRET", $wxxcx_config['app_secret'] ?? '', $realUrl);
        //curl请求
        $result = CurlBasiceService::getInstance()->httpGet($realUrl);

        $result = json_decode($result, true);
        if (!empty($result['session_key']) && !empty($param['encryptedData']) && !empty($param['iv'])){
            $pc = new WechatPhone($wxxcx_config['app_id'], $result['session_key']);
            $errCode = $pc->decryptData($param['encryptedData'], $param['iv'], $data );

            if ($errCode == 0) {
                return $this->codeSuccess(json_decode($data, true));
            }
        }

        return $this->codeError([], 1024, '参数错误');

    }

    public function sign_award(Request $request): ?Object
    {
        $userAll = UserSignModel::getUserData([], 'id', [1,2,3,4,5,6,7]);

        foreach ($userAll as &$value){
            $value['updated_at'] = date('Y-m-d H:i:s', $value['updated_at']);

            $value['award'] = json_decode($value['award'], true);

            $goods = array();
            //查询到所有商品信息
            if (!empty($value['award'])){
                $goods = GoodsModel::getPage(
                    [],
                    999,
                    'id, goods_name, goods_remark, original_img, price, fit_pets, type, weight, weight_type, weight_json',
                    'id',
                    array_column($value['award'], 'goods_id')
                );

                $goods = \App\Services\Web\UserService::getInstance()->handleGoodsResponse($goods);

                if (is_array($value['award'])){
                    $stringTemp = '';

                    foreach ($value['award'] as $ks => $vs){
                        if (!empty($goods[$vs['goods_id']])){
                            $value['award'][$ks]['original_img'] = $goods[$vs['goods_id']][0]['original_img'] ?? '';
                            $value['award'][$ks]['goods_message'] = $goods[$vs['goods_id']];
                            foreach ($goods[$vs['goods_id']] as $v){
                                $stringTemp .= '，' . $v['goods_name'] . ' * ' .  $vs['num'];
                            }

                        }
                    }
                    $value['goods_message'] = trim($stringTemp, '，');
                }
            }
        }

        return $this->codeSuccess($userAll);
    }

    /**
     * 地址列表
     * @param Request $request
     * @return object|null
     */
    public function get_city_china(Request $request): ?object
    {
        $params = $request->only(['parent_code', 'is_tree']);
        $params['is_tree'] = $params['is_tree'] ?? 2;
        if ($params['is_tree'] == 1){
            $res = CityChinaModel::getData([], '', [], 'code, parent_code, name');
            $res = makeTree($res, 'code', 'parent_code');

        }else{
            $res = CityChinaModel::getData(['parent_code' => $params['parent_code'] ?? 0], '', [], 'code, name');

        }

        return $this->codeSuccess($res);
    }

    /**
     * 信息类型列表
     * @param Request $request
     * @return object|null
     */
    public function get_tag(Request $request): ?object
    {
        $params = $request->only(['type','title','is_tree','cat_1']);

        $where = [];
        if (!(!empty($params['type']) && $params['type'] == 'all')){
            $where[] = ['parent_id', '=', 0];
        }

        if (!empty($params['title'])){
            $where[] = ['name', 'like', '%' . $params['title'] . '%'];
        }

        if (!empty($params['cat_1'])){
            unset($where);
            $where[] = ['parent_id_path', '=', $params['cat_1']];
        }

        $res = TagsModel::getUserDataCopy($where, '', [], 1, 'id, name, parent_id');

        if (!empty($params['is_tree']) && $params['is_tree'] == 2){
            $res = makeTree($res, 'id', 'parent_id');
        }

        $result = [];
        foreach ($res as $value){
            unset($temp_c);
            $temp_c['id'] = $value['id'];
            $temp_c['name'] = $value['name'];
            $temp_c['parent_id'] = $value['parent_id'];
            $temp_c['_child'] = [];
            if (!empty($value['_child'])){
                $temp_c_c = [];
                foreach ($value['_child'] as $vs){
                    if (!empty($vs['_child'])){
                        foreach ($vs['_child'] as $vs_c){
                            $temp_c_c[] = $vs_c;
                        }
                    }
                }
                $temp_c['_child'] = $temp_c_c;
            }
            $result[] = $temp_c;
        }

        return $this->codeSuccess($result);
    }

    /**
     * 用户列表
     * @param Request $request
     * @return Object|null
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function user_data(Request $request): ?Object
    {
        $params = $request->only(['job_num', 'nickname']);

        $params['type'] = 1;
        $result = \App\Services\Web\UserService::getInstance()->userAll($params);

        //获取数据  权限架构
        return $this->codeSuccess($result);
    }

    /**
     * 普通发布获取表单模板配置
     * @return void
     */
    public function get_table(Request $request): ?object
    {
        $params = $request->only(['id']);
        //获取表单模板内容
        $tag = TagsModel::getOneById($params['id'] ?? 0, 'name_msg');
        if (empty($tag['name_msg'])){
            return $this->codeError([], 1011, '分类无内容');
        }

        $tableInfo = TableModel::getSing(['msg'=> $tag['name_msg']], 'id, content');
        if (empty($tableInfo['content'])){
            return $this->codeError([], 1011, '分类无内容');

        }

        //查询字段属性
        $content = json_decode($tableInfo['content'], true);
        $item = TableItemModel::getUserData([], 'id', $content);

        foreach ($item as &$value){
            if (!empty($value['option_content'])){
                $value['option_content'] = json_decode($value['option_content'], true);
            }

            if (!empty($value['accessory_style'])){
                $value['accessory_style'] = json_decode($value['accessory_style'], true);
            }

            unset( $value['deleted_at']);
        }

        return $this->codeSuccess($item);
    }

    /**
     * 发布
     * @param Request $request
     * @return object|null
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function user_public(Request $request): ?object
    {
        $params = $request->only(['id', 'area_json', 'tag_json', 'cat_1', 'cat_2', 'admin_id', 'pay_num', 'share_style', 'cheer_money']);

        $bool = $this->handleIsNull($params, ['cat_1', 'admin_id', 'share_style']);

        if (!$bool){
            return $this->codeError([], 1011, '参数错误');

        }

        if (!empty($params['area_json'])){
            $params['area_json'] = array_merge([[adminUserInfo('area_province_id'), adminUserInfo('area_city_id'), adminUserInfo('area_district_id')]], $params['area_json']);
        }else{
            $params['area_json'] = [[adminUserInfo('area_province_id'), adminUserInfo('area_city_id'), adminUserInfo('area_district_id')]];
        }
        $params['area_json'] = json_encode($params['area_json']);

            $tag_json_arr = $params['tag_json'] ?? [];
        if (!empty($params['tag_json'])){
            $params['tag_json'] = json_encode($params['tag_json']);
        }

        $params['pay_sum'] = intval($params['pay_num']) + intval($params['cheer_money']);

        if ($params['pay_sum'] > 0){
            $params['style'] = 2;
        }

        if (!empty($params['id'])){
            return $this->codeError([], 1011, '不支持修改');


        }else{
            $info = UserPublicModel::getSingle();

            //获取分类首拼
            $name_msg =TagsModel::getSingle(['id'=> $params['cat_1']]);
            if (empty($name_msg['name_msg'])){
                return $this->codeError([], 1011, '一级分类不存在');

            }

            $noId = 1;
            if (!empty($info)){
                $noId = $info['id'] + 1;
            }

            $string = '';
            for ($i=0;$i<8-strlen($noId);$i++){
                $string .= '0';
            }

            if (($params['pay_num'] + $params['cheer_money']) > 0){
                //vip
                $no = $name_msg['name_msg'] . '-vip' . $string . $noId;

            }else{
                //普通
                $no = $name_msg['name_msg'] . '-' . $string . $noId;

            }

            //添加赋值
            $params['no'] = $no;
            $params['user_id'] = adminUserInfo('id');
            $params['created_at'] = time();
            $params['created_date'] = date('Ymd', time());
            $params['handle_time'] = date('H', time()) >= 18 ? (time() + (86400 / 2)) : time();
            $params['op_time'] = time();

            //任务初始发布地址-用户的地址
            $temp_area = json_decode($params['area_json'], true);
            $params['area'] = $temp_area[0][0] ?? 0;
            $params['city'] = $temp_area[0][1] ?? 0;
            $params['address'] = $temp_area[0][2] ?? 0;

            $public_id = UserPublicModel::insertSingle($params);
        }

        if (!empty($tag_json_arr)){
            foreach ($tag_json_arr as $vsl){
                TaskTagModel::insertSingle([
                    'tag'=> $vsl,
                    'task_id'=> $public_id,
                ]);
            }
        }

        if (empty($public_id)){
            return $this->codeError([], 1011, '入库失败，请联系管理员');
        }

        return $this->codeSuccess(['id'=> $public_id]);

    }

    /**
     * 搜索发布
     * @param Request $request
     * @return object|null
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function vip_public_three(Request $request): ?object
    {
        $params = $request->only(['province', 'city', 'district', 'seach_cat_1', 'seach_page', 'seach_count']);

        $bool = $this->handleIsNull($params, ['province', 'city', 'district', 'seach_cat_1', 'seach_page', 'seach_count']);

        if (!$bool){
            return $this->codeError([], 1011, '参数错误');
        }

        if (!in_array($params['seach_page'], [1,2,3])){
            return $this->codeError([], 1011, 'seach_page 参数错误');
        }

        if ($params['seach_count'] == 0){
            return $this->codeError([], 1011, 'seach_count 参数错误');
        }

        $order_arr_1 = OrderModel::getSingle(['seach_cat_1'=> $params['seach_cat_1'], 'seach_page'=> $params['seach_page'], 'status'=> 0]);
        if(!empty($order_arr_1)){
            return $this->codeError([], 1011, '该类型和排名已经有人拍下，未付款');
        }

        $order_arr_2 = OrderModel::getSingle(['seach_cat_1'=> $params['seach_cat_1'], 'seach_page'=> $params['seach_page'], 'status'=> 1, 'is_seach_end'=> 2]);
        if(!empty($order_arr_2)){
            return $this->codeError([], 1011, '该类型和排名没有空位了');
        }

        $money = 0;
        switch ($params['seach_page']){
            case 1:
                $money = $params['seach_count'];
                break;
            case 2:
                $money = $params['seach_count'] * 0.8;

                break;
            case 3:
                $money = $params['seach_count'] * 0.5;

                break;
        }
        //分
        $money = $money * 100;

        //修改任务
        $task_data = [
            'style'=> 3,
            'seach_area'=> json_encode([$params['province'], $params['city'], $params['district']]),
            'seach_cat_1'=> $params['seach_cat_1'],
            'seach_page'=> $params['seach_page'],
            'seach_count'=> $params['seach_count'],
            'seach_money'=> $money,
        ];
        $task_data['no'] = time() . rand(1000, 9999);
        $task_data['user_id'] = adminUserInfo('id');
        $task_data['created_at'] = time();
        $task_data['created_date'] = date('Ymd', time());
        $task_data['op_time'] = time();

        //任务初始发布地址-用户的地址
        $temp_area = json_decode($task_data['seach_area'], true);
        $task_data['area'] = $temp_area[0] ?? 0;
        $task_data['city'] = $temp_area[1] ?? 0;
        $task_data['address'] = $temp_area[2] ?? 0;

        $id = UserPublicSearchModel::insertSingle($task_data);
        return $this->codeSuccess(['id'=> $id]);
    }

    /**
     * 填充发布内容
     * @param Request $request
     * @return object|null
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function fill_user_public(Request $request): ?object
    {
        $params = $request->only(['id', 'tag_id', 'rpc_id', 'content', 'content_vip', 'is_search'
            , 'create_lxr_name', 'create_lxr_mobile', 'create_title', 'plain_end_time', 'wx_num', 'wx_qcode']);

        $bool = $this->handleIsNull($params, ['id', 'tag_id']);

        if (!$bool){
            return $this->codeError([], 1011, '参数错误');
        }

        $params['content'] = $params['content'] ?? [];
        $params['content_vip'] = $params['content_vip'] ?? '';
        $is_search = $params['is_search'] ?? 2;
        unset($params['is_search']);

        $tag = TagsModel::getOneById($params['tag_id'] ?? 0, 'name_msg');
        if (empty($tag['info_table'][0]['id'])){
            return $this->codeError([], 1011, '分类无内容');
        }
        $params['table_id'] = $tag['info_table'][0]['id'];
        unset($params['tag_id']);

        if ($is_search == 1){
            //搜索发布
            $userPublic = UserPublicSearchModel::getSingle(['id'=> $params['id']]);

        }else{
            $userPublic = UserPublicModel::getSingle(['id'=> $params['id']]);

        }

        $return = [];

        if (!empty($params['id'])){
            //修改
            if(!empty($params['plain_end_time'])){
                $params['plain_end_time'] = strtotime($params['plain_end_time']) + 86399;
            }else{
                $params['plain_end_time'] = time() + (86400 * 3);
            }
            $params['created_at'] = time();
            $params['updated_at'] = time();
            $params['done_time'] = time() + (86400 * 3);
            $params['content'] = json_encode($params['content']);
            $params['handle_time'] = date('H', time()) >= 18 ? (time() + (86400 / 2)) : time();
            $params['op_time'] = time();

            $style_temp = 0;
            $area_temp['area_money'] = 0;
            if((!empty($userPublic['pay_num']) && $userPublic['pay_num'] > 0) && (!empty($userPublic['cheer_money']) && $userPublic['cheer_money'] > 0)){
                //1vip打赏 2普通提效 3转vip 4退款 5vip打赏+提效 6普通订单 发布多地区 7三方平台提效
                $style_temp = 5;

            }else if(!empty($userPublic['pay_num']) && $userPublic['pay_num'] > 0){
                $style_temp = 1;

            }else if(!empty($userPublic['cheer_money']) && $userPublic['cheer_money'] > 0){
                $style_temp = 2;

            }else if(!empty($userPublic['seach_money'])){
                $style_temp = 7;

            }else{
                if (!empty($userPublic['area_json'])){
                    $city_arr = json_decode($userPublic['area_json'], true);
                    $city_arr_count = count($city_arr);
                    if ($city_arr_count < 2){
                        //只有一个发布地址 直接成功
//                        $params['is_pay'] = 1;
                        $params['status'] = 1;
                    }else{
                        //每多一个发布地址 多收一块钱
                        $style_temp = 6;
                        $area_temp['area_money'] = $area_temp['pay_sum'] = ($city_arr_count - 1) * 100;
                        UserPublicModel::updateSingle(['id'=> $userPublic['id']], $area_temp);
                    }
                }else{
                    //没有发布地址 直接成功
//                    $params['is_pay'] = 1;
                    $params['status'] = 1;
                }
            }

            if (!empty($style_temp)){
                //添加支付记录
                if ($style_temp <> 7){
                    $order_id = OrderModel::insertSingle([
                        'public_id'=> $userPublic['id'],
                        'money'=> $userPublic['pay_num'] + $userPublic['cheer_money'],
                        'status'=> 0,
                        'style'=> $style_temp,
                        'created_at'=> time(),
                        'user_id'=> adminUserInfo('id'),
                    ]);
                    UserPublicModel::updateSingle(['id'=> $params['id']], $params);

                }else{
                    $order_id = OrderModel::insertSingle([
                        'public_id'=> $userPublic['id'],
                        'money'=> $userPublic['seach_money'],
                        'status'=> 0,
                        'style'=> $style_temp,
                        'created_at'=> time(),
                        'user_id'=> adminUserInfo('id'),
                        'seach_cat_1'=> $userPublic['seach_cat_1'],
                        'seach_page'=> $userPublic['seach_page'],
                        'seach_count'=> $userPublic['seach_count'],
                        'is_seach'=> 1,
                        'is_seach_end'=> 2,
                    ]);

                    UserPublicSearchModel::updateSingle(['id'=> $params['id']], $params);
                }

                //进行支付逻辑
                $wxxcx_config = config('wechat.wxxcx');
                $appid=$wxxcx_config['app_id'];
                $openid= adminUserInfo('openid');
                $mch_id=$wxxcx_config['mch_id'];
                $key=$wxxcx_config['api_v2'];
                $out_trade_no = $order_id;//商户号
                //money不用多说了吧
                $total_fee = $userPublic['pay_num'] + $userPublic['cheer_money'] + $area_temp['area_money'] + $userPublic['seach_money'];

                //自定义参数 用于回调
                $notify_url = 'http://hxbfb.bailingkeji.com/login/callback-order';
                $body = "支付";
                $weixinpay = new WechatPayV2($appid,$openid,$mch_id,$key,$out_trade_no,$body,'',$total_fee,$notify_url);
                $return=$weixinpay->pay();
            }else{
                UserPublicModel::updateSingle(['id'=> $params['id']], $params);

            }

        }else{
            return $this->codeError([], 1011, 'id不能为空');

        }

        return $this->codeSuccess($return);
    }

    /**
     * 填充发布内容
     * @param Request $request
     * @return object|null
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function refresh_change_vip(Request $request): ?object
    {
        $params = $request->only(['id', 'pay_num']);

        $bool = $this->handleIsNull($params, ['id', 'pay_num']);

        if (!$bool){
            return $this->codeError([], 1011, '参数错误');

        }

        $userPublic = UserPublicModel::getSingle(['id'=> $params['id']]);
        if (empty($userPublic)){
            return $this->codeError([], 1011, '不存在');

        }

        if ($userPublic['style'] == 2){
            return $this->codeError([], 1011, '已经是vip订单了');

        }

        $order_bool = OrderModel::getSingle(['id'=> $params['id'], 'style'=> 3], 'status', [0,1]);
        if (!empty($order_bool)){
            return $this->codeError([], 1011, '订单已经有人在支付了');
        }

        $return = [];
        if (!empty($params['id'])){
            //修改
            $params['plain_end_time'] = time() + (86400 * 3);
            $params['created_at'] = time();
            $params['updated_at'] = time();
            $params['done_time'] = time() + (86400 * 3);
            $params['handle_time'] = date('H', time()) >= 18 ? (time() + (86400 / 2)) : time();
            $params['op_time'] = time();

            if (!empty($params['pay_num']) && $params['pay_num'] > 0){
                //添加支付记录
                $order_id = OrderModel::insertSingle([
                    'public_id'=> $params['id'],
                    'money'=> $params['pay_num'],
                    'status'=> 0,
                    'style'=> 3,
                    'user_id'=> adminUserInfo('id'),
                    'created_at'=> time(),
                ]);

                //修改任务表
                UserPublicModel::updateSingle(['id'=> $params['id']], [
                    'pay_num'=> $params['pay_num'],
                    'pay_sum'=> $params['pay_num'],
                ]);

                //进行支付逻辑
                $wxxcx_config = config('wechat.wxxcx');

                $appid=$wxxcx_config['app_id'];
                $openid= adminUserInfo('openid');
                $mch_id=$wxxcx_config['mch_id'];
                $key=$wxxcx_config['api_v2'];
                $out_trade_no = $order_id;//商户号
                //money不用多说了吧
                $total_fee = $userPublic['pay_num'];
                //自定义参数 用于回调
                $notify_url = 'http://hxbfb.bailingkeji.com/login/callback-order';
                $body = "支付";
                $weixinpay = new WechatPayV2($appid,$openid,$mch_id,$key,$out_trade_no,$body,'',$total_fee,$notify_url);
                $return=$weixinpay->pay();
            }else{
                return $this->codeError([], 1011, '金额异常');

            }
            $params['style'] = 2;
            UserPublicModel::updateSingle(['id'=> $params['id']], $params);

        }else{
            return $this->codeError([], 1011, 'id不能为空');

        }

        return $this->codeSuccess($return);
    }


    /**
     * VIP发布
     * @param Request $request
     * @return object|null
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function vip_public(Request $request): ?object
    {
        $params = $request->only(['admin_id', 'pay_num']);

        $bool = $this->handleIsNull($params, ['admin_id', 'pay_num']);

        if (!$bool){
            return $this->codeError([], 1011, '参数错误');

        }

        $info = UserPublicModel::getSingle();

        //添加赋值
        $params['no'] = adminUserInfo('id') . time() . rand(1000, 9999);
        $params['style'] = 2;
        $params['user_id'] = adminUserInfo('id');
        $params['created_at'] = time();
        $params['handle_time'] = date('H', time()) >= 18 ? (time() + (86400 / 2)) : time();

        // todo 唤起支付（支付回调：成功后修改任务状态）


        UserPublicModel::insertSingle($params);

        return $this->codeSuccess();
    }

    /**
     * 表单预览
     * @return void
     */
    public function table_preview(Request $request): ?object
    {
        $params = $request->only(['id', 'content']);

        $bool = $this->handleIsNull($params, ['id', 'content']);

        if (!$bool){
            return $this->codeError([], 1011, '参数错误');

        }

        $infoMsg = $this->handlePreview($params['id'], $params['content']);

        return $this->codeSuccess(['info_msg'=> $infoMsg]);

    }

    public function handlePreview($tableId, $publicContent)
    {
        //根据信息类型id获取，模板编号
        $info = TableModel::getOneById($tableId, '*');
        $info['content_insert'] = json_decode($info['content_insert'], true);

        if (empty($info['msg'])){
            return false;

        }

        $tmp = enum_wechat::TEMP;
        $infoMsg = $tmp[$info['msg']];

        $list = array_column($publicContent, null, 'id');

        //根据title换参数
        if (!empty($info['content_insert']['title'])){
            foreach ($info['content_insert']['title'] as $keys => $value){
                $artTemp = '';
                foreach ($value as $vs){
                    if (!empty($list[$vs]['content'])){
                        $artTemp .= ',' . $list[$vs]['content'];
                    }
                }
                $artTemp = trim($artTemp, ',');
                $infoMsg = str_replace("TITLE" . ($keys + 1), $artTemp ?? '', $infoMsg);

            }
        }

        //根据content换参数
        if (!empty($info['content_insert']['content'])){
            foreach ($info['content_insert']['content'] as $keys => $value){
                $artTemp = '';
                foreach ($value as $vs){
                    if (!empty($list[$vs]['content'])){
                        $artTemp .= ',' . $list[$vs]['content'];
                    }
                }
                $artTemp = trim($artTemp, ',');
                $infoMsg = str_replace("CONTENT" . ($keys + 1), $artTemp ?? '', $infoMsg);

            }
        }

        return $infoMsg;
    }

    /**
     * 刷新信息列表
     * @return void
     */
    public function refresh_message(Request $request): ?object
    {
        $params = $request->only(['no', 'cat_1', 'style', 'admin_id', 'page', 'limit']);

        $where = [];
        if (!empty($params['no'])){
            $where['no'] =  $params['no'];
        }

        if (!empty($params['cat_1'])){
            $where['cat_1'] =  $params['cat_1'];
        }

        if (!empty($params['style'])){
            $where['style'] =  $params['style'];
        }

        if (!empty($params['admin_id'])){
            $where['admin_id'] =  $params['admin_id'];
        }

        $where['user_id'] =  adminUserInfo('id');
        $where[] =  ['status', '>', 0];

        $userList = UserPublicModel::getPage($where, $params['limit'] ?? 15);

        $list = [];
        foreach ($userList['data'] as $value){
            unset($temp);
            $temp['id'] = $value['id'] ?? '';
            $temp['no'] = $value['no'] ?? '';
            $temp['style'] = $value['style'] ?? '';
            $temp['pay_num'] = $value['pay_num'] ?? '';
            $temp['admin_name'] = '';
            $temp['created_at'] = date('Y-m-d H:i:s', $value['created_at']) ?? '';
            $temp['status'] = $value['status'] ?? '';
            $temp['refresh_times'] = $value['refresh_times'] ?? 0;
            $temp['create_lxr_name'] = $value['create_lxr_name'] ?? '';
            $temp['create_lxr_mobile'] = $value['create_lxr_mobile'] ?? '';
            $temp['create_title'] = $value['create_title'] ?? '';
            $temp['plain_end_time'] = date('Y-m-d H:i:s', $value['plain_end_time']) ?? '';

            $temp_cat_msg = [];
            if (!empty($value['cat_1'][0]['name'])){
                $temp_cat_msg[] = $value['cat_1'][0]['name'];
            }

            if (!empty($value['cat_2'][0]['name'])){
                $temp_cat_msg[] = $value['cat_2'][0]['name'];
            }

            $temp['cat_msg'] = implode(',', $temp_cat_msg);


            if (!empty($value['admin_name'][0]['nickname'])){
                $temp['admin_name'] = $value['admin_name'][0]['nickname'];
            }

            //44完成-评论按钮
            if ((!empty($value['done_time']) && (time() - (86400*5) > $value['done_time']))
            || !empty($value['user_is_finsh'])){
                $temp['status'] = 44;

                //45完成-置灰评论按钮
                if (!empty($value['visit_appraise'])){
                    $temp['status'] = 45;
                }
            }

            //46 退款中
            $temp['order_out_money_created'] = 0;
            if(!empty($value['order_out_money'][0]['created_at'])){
                $temp['order_out_money_created'] = $value['order_out_money'][0]['created_at'];
            }

            //  普通订单：1待编辑、6待发布、5完成-完成按钮、44完成-评论按钮、45完成-置灰评论按钮。
            //VIP订单：1待编辑、6待发布、41引流、42匹配、43搜索、44完成-评论按钮、45完成-置灰评论按钮

            //微服务id
            $temp['rpc_id'] = $value['rpc_id'] ?? '';

            $list[] = $temp;
        }
        $userList['data'] = $list;
        return $this->codeSuccess(FormatBase::listData($userList));
    }

    /**
     * 刷新信息列表-点击刷新
     * @param Request $request
     * @return object|null
     */
    public function refresh_click(Request $request): ?object
    {
        $params = $request->only(['id']);

        $bool = $this->handleIsNull($params, ['id']);

        if (!$bool){
            return $this->codeError([], 1011, '参数错误');

        }

        foreach ($params['id'] as $value){
            UserPublicModel::addIncrementValue(['id'=> $value], 'refresh_times', 1, '', [], ['refresh_at'=> time()]);

        }
        return $this->codeSuccess();

    }

    /**
     * 信息列表-评论
     * @param Request $request
     * @return object|null
     */
    public function refresh_comment(Request $request): ?object
    {
        $params = $request->only(['id', 'content']);

        $bool = $this->handleIsNull($params, ['id', 'content']);

        if (!$bool){
            return $this->codeError([], 1011, '参数错误');

        }

        UserPublicModel::updateSingle(['id'=> $params['id']], [
            'visit_appraise'=> $params['content']
        ]);

        return $this->codeSuccess();

    }

    /**
     * 信息列表-评论
     * @param Request $request
     * @return object|null
     */
    public function refresh_finsh(Request $request): ?object
    {
        $params = $request->only(['id']);

        $bool = $this->handleIsNull($params, ['id']);

        if (!$bool){
            return $this->codeError([], 1011, '参数错误');

        }

        UserPublicModel::updateSingle(['id'=> $params['id']], [
            'user_is_finsh'=> 1
        ]);

        return $this->codeSuccess();

    }

    /**
     * 信息列表-评论
     * @param Request $request
     * @return object|null
     */
    public function refresh_refer_money(Request $request): ?object
    {
        $params = $request->only(['id']);

        $bool = $this->handleIsNull($params, ['id']);

        if (!$bool){
            return $this->codeError([], 1011, '参数错误');

        }

        //获取任务
        $userPublic = UserPublicModel::getSingle(['id'=> $params['id']]);
        if (empty($userPublic) || $userPublic['pay_sum'] <= 0){
            return $this->codeError([], 1011, '不支持退款');
        }

        //获取订单金额
        $order = OrderModel::getUserData(['public_id'=> $params['id'], 'status'=> 1]);
        if (empty($order)){
            return $this->codeError([], 1011, '不支持退款');
        }

        $order_refer = OrderModel::getUserData(['public_id'=> $params['id'], 'status'=> 3, 'style'=> 4]);
        if (!empty($order_refer)){
            return $this->codeError([], 1011, '已经申请过退款了，请稍后');
        }

        OrderModel::insertSingle([
            'public_id'=> $params['id'],
            'money'=> array_sum(array_column($order, 'money')),
            'status'=> 3,
            'style'=> 4,
            'created_at'=> time(),
            'user_id'=> adminUserInfo('id'),

        ]);

        return $this->codeSuccess();
    }

    /**
     * 消息列表
     * @return void
     */
    public function message_list(Request $request): ?object
    {
        $params = $request->only(['page', 'limit', 'no']);

        if (!empty($params['no'])){
            $where[] = ['up.no', 'like', '%' . $params['no'] . '%'];
        }
        $where['up.user_id'] = adminUserInfo('id');

        $userList = OpLogsModel::getPage($where, $params['limit'] ?? 15
            , '*', 'info_op_logs.style',[4,5]);

        //修改 is_show
        $update_data = OpLogsModel::getUserData(['up.user_id'=> adminUserInfo('id')], 'info_op_logs.style', [4,5], 5000);
        $update_data = array_column($update_data, 'id');

        OpLogsModel::updateSingle([], ['is_show'=> 2], 'id', $update_data);

        $list = [];
        foreach ($userList['data'] as $value){
            unset($temp);
            $temp['id'] = $value['id'] ?? '';
            $temp['style'] = $value['style'] ?? '';
            $temp['msg'] = $value['msg'] ?? '';
            $temp['created_at'] = $value['created_at'] ?? '';
            $temp['op_user_id'] = $value['op_user_id'] ?? '';
            $temp['rpc_id'] = $value['rpc_id'] ?? '';
            $temp['no'] = $value['no'] ?? '';
            $temp['op_user_id_msg'] = '';
            $temp['cat_1_msg'] = '';
            $temp['cat_2_msg'] = '';
            $temp['is_show'] = $value['is_show'] ?? '';

            if (!empty($value['sys_users'][0]['nickname'])){
                $temp['op_user_id_msg'] = $value['sys_users'][0]['nickname'];
            }

            if (!empty($value['cat_1'][0]['name'])){
                $temp['cat_1_msg'] = $value['cat_1'][0]['name'];
            }

            if (!empty($value['cat_2'][0]['name'])){
                $temp['cat_2_msg'] = $value['cat_2'][0]['name'];
            }

            $list[] = $temp;
        }
        $userList['data'] = $list;

        return $this->codeSuccess(FormatBase::listData($userList));
    }

    //message_read_none
    public function message_read_none(Request $request): ?object
    {
        $params = $request->only(['page', 'limit']);

        //修改 is_show
        $update_data = OpLogsModel::getUserData(['up.user_id'=> adminUserInfo('id'), 'is_show'=> 1], 'info_op_logs.style', [4,5], 5000);

        return $this->codeSuccess(['count'=> count($update_data)]);
    }

    public function message_update_data(Request $request): ?object
    {
        $params = $request->only(['id']);

        $bool = $this->handleIsNull($params, ['id']);

        if (!$bool){
            return $this->codeError([], 1011, '参数错误');

        }

        //获取消息详情
        $messageInfo = UserMessageModel::getOneById($params['id'], '*');

        if (empty($messageInfo['table_id']) || empty($messageInfo['user_public_id'])){
            return $this->codeError([], 1011, '数据错误');

        }

        //获取用户发布的内容
        $publicInfo = UserPublicModel::getOneById($messageInfo['user_public_id'], '*');
        $contentList = [];
        if (!empty($publicInfo['content'])){
            $contentList = array_column(json_decode($publicInfo['content'], true), null, 'id');

        }

        //获取表单item
        $tableInfo = TableModel::getOneById($messageInfo['table_id'], '*');
        if (empty($tableInfo['content'])){
            return $this->codeError([], 1011, '数据错误');

        }

        //获取表单的item
        $itemList = TableItemModel::getUserData([], 'id', json_decode($tableInfo['content'], true));

        //循环表单，插入用户发布的内容
        foreach ($itemList as &$value){
            if (!empty($contentList[$value['id']])){
                $value['content'] = $contentList[$value['id']]['content'];
                $value['field'] = $contentList[$value['id']]['field'];
            }else{
                $value['content'] = '';
                $value['field'] = '';
            }
        }


        //返回
        return $this->codeSuccess($itemList);

    }


    public function public_detail(Request $request): ?object
    {
        $params = $request->only(['id']);

        return $this->codeSuccess();

    }

    //type 1 首页-查看订单历史记录 2 首页-查看订单服务情况
    public function get_all_order_logs(Request $request): ?object
    {
        $params = $request->only(['page', 'limit', 'type', 'published', 'cat_1', 'style', 'no', 'style_type', 'task_id']);

        $params['type'] = $params['type'] ?? 1;

        if ($params['type'] == 1){
            $userList = UserService::getInstance()->handleorder($params);

        }else{
            $userList = UserService::getInstance()->handleOrderLogs($params);

        }
        return $this->codeSuccess(FormatBase::listData($userList));

    }

    //get_all_task_cat
    public function get_all_task_cat(Request $request): ?object
    {
        $params = $request->only([]);
        $res = UserPublicModel::getUserDataWithTag(['status'=> 1, ['plain_end_time', '>', time()], 'user_id'=> adminUserInfo('id')]);
        $data = [];
        foreach ($res as $value){
            unset($temp);
            $temp['task_id'] = '';
            $temp['id'] = '';
            $temp['name'] = '';
            $temp['name_msg'] = '';
            if (!empty($value['id'])){
                $temp['task_id'] = $value['id'];
            }
            if (!empty($value['tag_id'][0]['id'])){
                $temp['id'] = $value['tag_id'][0]['id'];
            }
            if (!empty($value['tag_id'][0]['name'])){
                $temp['name'] = $value['tag_id'][0]['name'];
            }
            if (!empty($value['tag_id'][0]['name_msg'])){
                $temp['name_msg'] = $value['tag_id'][0]['name_msg'];
            }

            $data[] = $temp;
        }
        return $this->codeSuccess($data);
    }

    /**
     * 首页-任务详情
     * @return void
     */
    public function task_detail(Request $request): ?object
    {
        $params = $request->only(['id']);
        if (empty($params['id'])){
            return $this->codeError([], 1011, '参数错误');
        }

        $public = UserPublicModel::getSingle(['id'=> $params['id']]);

        $public['cat_1_msg'] = '';
        if (!empty($public['cat_1'][0]['name'])){
            $public['cat_1_msg'] = $public['cat_1'][0]['name'];
        }

        $public['cat_2_msg'] = '';
        if (!empty($public['cat_2'][0]['name'])){
            $public['cat_2_msg'] = $public['cat_2'][0]['name'];
        }

        //地区
        //发布地区
        $public['area_json_msg'] = [];
        if (!empty($public['area_json'])){
            $public['area_json'] = json_decode($public['area_json'], true);
            $citu_ids = [];
            if (!empty($public['area_json']) && is_array($public['area_json'])){
                foreach ($public['area_json'] as $vs_1){
                    foreach ($vs_1 as $vs_2){
                        $citu_ids[] = $vs_2;
                    }
                }

                $city_all = CityChinaModel::getUserData([], 'code', $citu_ids);
                $city_all = array_column($city_all, null,'code');

                foreach ($public['area_json'] as $vs_1){
                    $public_city = [];
                    foreach ($vs_1 as $vs_2){
                        if (!empty($city_all[$vs_2]['name'])){
                            $public_city[] = $city_all[$vs_2]['name'];
                        }
                    }
                    $public['area_json_msg'][] = $public_city;
                }
            }else{
                $public['area_json_msg'] = [];
            }
        }

        if (!empty($public['tag_json'])){
            $public['tag_json'] = json_decode($public['tag_json'], true);
        }else{
            $public['tag_json'] = [];
        }

        if (!empty($public['content'])){
            $public['content'] = json_decode($public['content'], true);
        }else{
            $public['content'] = [];
        }

        unset($public['cat_1'], $public['cat_2']);

        return $this->codeSuccess($public);
    }

    /**
     * 首页-查看订单历史记录
     * @return void
     */
    public function get_all_order(Request $request): ?object
    {
        $params = $request->only(['page', 'limit', 'published', 'cat_1', 'style', 'no']);
        $userList = UserService::getInstance()->handleorder($params);
        return $this->codeSuccess(FormatBase::listData($userList));
    }

    /**
     * 首页-查看订单服务情况
     * @return void
     */
    public function get_order_logs(Request $request): ?object
    {
        $params = $request->only(['page', 'limit', 'published', 'cat_1', 'style', 'no', 'style', 'style_type', 'task_id']);

        $userList = UserService::getInstance()->handleOrderLogs($params);

        return $this->codeSuccess(FormatBase::listData($userList));
    }

    /**
     * 首页-查看订单服务情况
     * @return void
     */
    public function get_order_search_logs(Request $request): ?object
    {
        $params = $request->only(['page', 'limit', 'published', 'cat_1', 'style', 'no', 'style', 'style_type', 'task_id']);

        $userList = UserService::getInstance()->handleOrderLogsSearch($params);

        return $this->codeSuccess(FormatBase::listData($userList));
    }

    public function get_my_time(Request $request): ?object
    {
        $params = $request->only(['page', 'limit']);

        $userList = UserPublicModel::getUserData(['user_id'=> adminUserInfo('id'), 'status'=> 5]);

        $num = 0;
        foreach ($userList as $value){
            $temp = $value['plain_end_time'] - $value['done_time'];
            if ($temp > 0){
                $num += $temp;
            }
        }


        return $this->codeSuccess(['time'=> $num]);
    }

    //delete_phone
    public function delete_phone(Request $request): ?object
    {
        $params = $request->only(['id']);

        UserModel::updateSingle(['id'=> $params['id']], [
            'mobile'=> ''
        ]);

        return $this->codeSuccess();
    }

    public function pay_config_list(Request $request): object
    {
        $params = $request->only([]);
        $data = PayConfigModel::getUserData();

        return $this->codeSuccess($data);

    }

    public function search_refresh_message(Request $request): object
    {
        $params = $request->only(['day_type', 'time_type', 'cat_1', 'no', 'mobile', 'number', 'area', 'city', 'address', 'limit', 'page'
            , 'sys_user_id', 'style', 'content_vip', 'is_order_plain_end_time', 'admin_id']);

        if(empty($params['day_type'])){
            $params['day_type'] = 1;
        }

        //添加筛选条件
        $where = TaskService::getInstance()->handleTaskSearch($params, 2);
        //排序
        $order = [];
        if(!empty($params['is_order_plain_end_time'])){
            $order = ['plain_end_time', $params['is_order_plain_end_time'] == 1 ? 'asc' : 'desc'];
        }
        $where[] = ['info_user_public_search.user_id', '=', adminUserInfo('id')];

        $list = UserPublicSearchModel::getPageJoinUser($where, $params['limit'] ?? 15
            , 'info_user_public_search.*, info_user.id as user_id, info_user.nickname, info_user.number'
            , '', [], $order, $params, [0, 9]);

        foreach ($list['data'] as &$value){
            //分类
            if (!empty($value['cat_2_msg'][0]['name'])){
                $value['cat_2_msg'] = $value['cat_2_msg'][0]['name'];

            }else{
                $value['cat_2_msg'] = '';

            }

            if (!empty($value['cat_1_msg'][0]['name'])){
                $value['cat_1_msg'] = $value['cat_1_msg'][0]['name'];

            }else{
                $value['cat_1_msg'] = '';

            }

            //维护人id
            $value['admin_nickname'] = '';
            if (!empty($value['admin_msg'][0]['nickname'])){
                $value['admin_nickname'] = $value['admin_msg'][0]['nickname'];
            }

            //用户手机号
            $value['user_mobile'] = '';
            if (!empty($value['users'][0]['mobile'])){
                $value['user_mobile'] = $value['users'][0]['mobile'];
            }

            //地区
            $area_whole_msg = [];
            if (!empty($value['area_msg'][0]['name'])){
                $area_whole_msg[] = $value['area_msg'][0]['name'];
            }

            if (!empty($value['city_msg'][0]['name'])){
                $area_whole_msg[] = $value['city_msg'][0]['name'];
            }

            if (!empty($value['address_msg'][0]['name'])){
                $area_whole_msg[] = $value['address_msg'][0]['name'];
            }

            if (!empty($area_whole_msg)){
                $value['area_whole_msg'] = implode('-', $area_whole_msg);

            }else{
                $value['area_whole_msg'] = '';
            }

            $value['use_seach_count'] = 0;
            if (!empty($value['search_log'])){
                $value['use_seach_count'] = count($value['search_log']);
            }

            //结束时间
            $value['done_time'] = date('Y-m-d H:i:s', $value['done_time']);

            //创建时间
            $value['created_at'] = date('Y-m-d H:i:s', $value['created_at']);

            //操作时间
            $value['op_time'] = date('Y-m-d H:i:s', $value['op_time']);

            $value['one_money'] = '';
            //用于计算剩余点数
            $one_money = 0;
            //单价
            if (!empty($value['seach_page'])){
                switch ($value['seach_page']){
                    case 1:
                        $value['one_money'] = '1.00/PV';
                        $one_money = 1;
                        break;
                    case 2:
                        $value['one_money'] = '0.80/PV';
                        $one_money = 0.8;

                        break;
                    case 3:
                        $value['one_money'] = '0.50/PV';
                        $one_money = 0.5;

                        break;
                }
            }

            //剩余点数
            $value['let_money'] = '';
            if (!empty($value['seach_page']) && !empty($value['seach_count']) && !empty($value['seach_money']) && !empty($one_money)){
                $value['let_money'] = $value['seach_money'] - ($value['seach_count'] * $one_money);
            }

            unset($value['admin_msg']);
        }

        return $this->codeSuccess(FormatBase::listData($list));
    }

}
